﻿using UnityEngine;
using System.Collections;

[RequireComponent (typeof(CharacterMotor))]
[AddComponentMenu ("Character/FPS Input Controller")]
public class FPSInputController : MonoBehaviour {

	private CharacterMotor motor;
	private float wheelSpeed =5.0f;
	private float mouseWheel = 0;
	// Use this for initialization
	public float camSens = 0.25f; 
	//public GameObject matBG;
	public bool wheelToMove ;
	private Vector3 lastMouse = new Vector3(255, 255, 255);
	private bool iOS_isDrag = false;
	private bool isDrag = false;
	private float pinchValue  = 0;
	private int preTouchCount = 0;
	private float lastDist ;
	private float curDist ;
	private float ww = 0;
	private float hh = 0;
	public float holdToMove = 0.5f;
	//=======Duc ++=======
	public float doubleClickMaxDistance = 1;
	private GameObject myTrigger ;
	private float touch_period = 0;
	private bool touch_1 = false;
	private float doubleClickTime = 0.5f;
	private NavMeshAgent nav ;
	private float stuckFrameCount  = 0;
	private Vector3 priorPosistion ;
	private bool navDesRefine ;
	private Vector3 navDesPos;
	
	public float nav_safeDistance = 1;
	
	private int nav_frameCount = 0;
	public bool MovementDirty = false;
	private SettingScript settingSc;
	private GameObject settingObj;
	private CharacterController charController;
	private Vector3 direct = Vector3.zero;
	//====================
	void Awake () {
		ww = Screen.width/5.0F;
		hh = Screen.height/3.0F;
		NotificationCenter.DefaultCenter.AddObserver(this, "OnIdle");
		NotificationCenter.DefaultCenter.AddObserver(this, "OnWake");
		nav = (NavMeshAgent)this.gameObject.GetComponent(typeof(NavMeshAgent));
		motor =  (CharacterMotor)this.gameObject.GetComponent(typeof(CharacterMotor));
		charController = (CharacterController)this.gameObject.GetComponent(typeof(CharacterController));
		myTrigger = GameObject.Find("Trigger").gameObject;
		settingObj = GameObject.Find("SettingGUI").gameObject;
	}
	

	void Update () {
		
		settingSc = (SettingScript)settingObj.GetComponent(typeof(SettingScript)); 
		nav.speed = settingSc.camSpeedScroll;
			//=======Duc ++=======
		if(!nav.hasPath)// || nav.remainingDistance.ToString() == "Infinity")
		{
			if(navDesRefine)
			{
				navDesPos.y = nav.transform.position.y;
				nav.destination = navDesPos;
				navDesRefine = false;
			}
			else
			{
				BroadcastMessage ("ControlAble", true);
			}		
		}
		else
		{
			//Neu sau 5 frame ma nav dung yen (vuong collider) thi tat nav
			if(nav.velocity == Vector3.zero)
			{
				if(nav_frameCount > 5)
				{
					BroadcastMessage ("ControlAble", true);
				}
				nav_frameCount++;
			}
			navDesRefine = false;
		}
		//====================
		if(wheelToMove)
		{
			if(stuckFrameCount < 10)
			{
				mouseWheel +=Input.GetAxis("Mouse ScrollWheel")*wheelSpeed;
				if (mouseWheel>0.01f)
					mouseWheel -= 0.01f;
				if (mouseWheel<-0.01f)
					mouseWheel += 0.01f;
				if(mouseWheel != 0)
				{	
					if(Vector3.Distance(transform.position, priorPosistion) < 0.007f)
					{		
						stuckFrameCount++;
					}
					else
					{		
						stuckFrameCount = 0;
					}
					priorPosistion = transform.position;
				}
			}
			else
			{			
				mouseWheel = 0;		
				stuckFrameCount = 0;
			}
		}
		else
		{
			mouseWheel = 0;		
		}
		
		// Get the input vector from kayboard or analog stick
		var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")+mouseWheel);
		direct = directionVector;
		if (Input.touchCount>=2)
		{ 
			
	  		var touch1 = Input.GetTouch(0);
	        var touch2 = Input.GetTouch(1);
	       	if (preTouchCount >= Input.touchCount)
	        	curDist = Vector2.Distance(touch1.position, touch2.position);
	        else
	        	curDist = lastDist;
	
	        if(curDist < lastDist)	
		    {
		        pinchValue -= Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition) *0.01f;
		        	
		    }
		    else
		    	if(curDist > lastDist)	
		    	{		
		        	pinchValue += Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition)*0.01f ;
		    	}		    
	  		//if((Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved))
	  
			lastDist = Vector2.Distance(touch1.position, touch2.position);			
		}		
		else
		{
			iOS_isDrag = false;
			//if (Input.GetMouseButton(0) && isDrag && (!matBG.guiTexture.HitTest(Input.mousePosition) || matBG.active == false))
			if (Input.GetMouseButton(0) && isDrag && !AllHitTest())		 
			{			
				if (Input.touchCount > 0)			
		    		lastMouse = new Vector3 (Input.GetTouch(0).position.x - lastMouse.x,Input.GetTouch(0).position.y - lastMouse.y,0);
				else
					lastMouse = Input.mousePosition - lastMouse ;
	
				if ( Input.touchCount > 0)
		    		lastMouse = Input.GetTouch(0).position;
				else
					lastMouse = Input.mousePosition;				
		    }
		    else
		    {
				if (Input.GetMouseButton(0))
				{
					isDrag = true;
					if ( Input.touchCount > 0)
			    		lastMouse = Input.GetTouch(0).position; 					
					else
						lastMouse = Input.mousePosition;
				}
				else
					isDrag = false;
			}
			//=======Duc ++=======
			//if(Input.GetMouseButtonDown(0) && (!matBG.guiTexture.HitTest(Input.mousePosition) || matBG.active == false))
			if(Input.GetMouseButtonDown(0))
			{	
				touch_1 = !touch_1;
				if(!AllHitTest())
				{	
					if(!touch_1)//If getting double click
					{				
						touch_1 = false;
						touch_period = 0;
						var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
						RaycastHit hit;
					    if(Physics.Raycast(ray, out hit, 10000))
					    {
					    	Debug.Log(""+hit.collider.name);
					    	BroadcastMessage ("ControlAble", false);
				   		 	nav_frameCount = 0;
		 			   		//nav.destination = Vector3(hit.point.x, hit.point.y, hit.point.z);
		 			   		Vector3 gotoPos  = nav.transform.position - hit.point;
		 			   		gotoPos = hit.point + gotoPos.normalized * nav_safeDistance;
		 			   		Debug.DrawLine(nav.transform.position, gotoPos, Color.blue, 1);
		 			   		nav.destination = gotoPos;
		 			   		navDesPos = gotoPos;
		 			   		MovementDirty = true;
				   		 	if(!nav.hasPath)
				   		 	{	
				   		 		navDesRefine = true;
	//			   		 		//Debug.Log(""+nav.destination);	   		 	
	//			   		 		nav.destination = Vector3(hit.point.x, nav.transform.position.y, hit.point.z);	
				   		 	}
				   		 	
				   			//Debug.Log("AAAAAAAAAAA");
				   		}
					}				
					else if(nav.hasPath)
					{
						//Debug.Log("BBBBBBBB");
						nav.destination = nav.transform.position;				
						nav.Stop();
					}
				}
				else if(nav.hasPath)
				{
					BroadcastMessage ("ControlAble", true);
				}
			}
			//====================
		}
		
		if(touch_1)
		{	
			touch_period += Time.deltaTime;
		}
		if(touch_period >= doubleClickTime)
		{
			touch_1 = false;
			touch_period = 0;
		}

		pinchValue -=  pinchValue*0.1f;
	
		directionVector.z += pinchValue;	
		if (directionVector != Vector3.zero) {
			
		}
		
				
		// Apply the direction to the CharacterMotor
		motor.inputMoveDirection = transform.rotation * directionVector;
		motor.inputJump = Input.GetButton("Jump");
		preTouchCount = Input.touchCount;
	}
		public void ControlAble(bool able )
		{
			charController.enabled = able;
			motor.enabled = able;
			nav.enabled = !able;
		}
		//======Duc ++=======
		private bool AllHitTest()
		{
			if(Camera.main != null)
			{
				GUILayer guiL = Camera.main.GetComponent(typeof(GUILayer)) as GUILayer;
				GUIElement guiE = guiL.HitTest(Input.mousePosition);
				if(guiE != null)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		void OnIdle()
		{	
			myTrigger.active = false;
		}
		void OnWake()
		{	
			myTrigger.active = true;
		}
		//===================
	// RequgameObjecte a character controller to be attached to the same game object
	

}